package cn.xiuxius.embedded.command.run;

import cn.xiuxius.embedded.command.TaskCommand;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import picocli.CommandLine.Option;
import picocli.CommandLine;

import java.util.concurrent.Callable;

@CommandLine.Command(name = "run",
        description = "Run command",
        mixinStandardHelpOptions = true
)
@Slf4j
@Getter
public class RunCommand implements Callable<Integer> {


    @CommandLine.ParentCommand
    private TaskCommand taskCommand;


    @Option(names = {"-c", "--clean"}, description = "Clean before run")
    private boolean clean;

    @Override
    public Integer call() {
        if (taskCommand == null) {
            CommandLine.usage(this, System.out);
            return 1;
        }

        if (taskCommand.prepare() != 0) {
            return 1;
        }

        if (clean) {
            new CommandLine(new TaskCommand()).execute("clean");
        }
        int build = new CommandLine(new TaskCommand()).execute("build");
        if (build != 0) {
            return 1;
        }
        if (taskCommand.getConfig().getStcgl().isAdvance()) {
            int flashAdv = new CommandLine(new TaskCommand()).execute("flash", "adv");
            if (flashAdv != 0) {
                return 1;
            }
        }else {
            int flashBase = new CommandLine(new TaskCommand()).execute("flash", "base");
            if (flashBase != 0) {
                return 1;
            }
        }
        return 0;
    }
}
